package com.mhc.suzuki.controller;

import com.alibaba.fastjson.JSON;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.constant.IdCardSideEnum;
import com.mhc.suzuki.constant.OssConfig;
import com.mhc.suzuki.util.DateUtil;
import com.mhc.suzuki.util.HttpUtils;
import com.mhc.suzuki.vo.IdCardVO;
import com.subaru.common.entity.BizResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * OCR识别管理
 * Created by kanon on 17/10/09 19:18.
 */
@Slf4j
@RestController
@RequestMapping(value = "/ocr")
public class OcrController {

    @Autowired
    private OssConfig ossConfig;

    /**
     * ocr识别身份证
     * @param base64IdCard
     * @param side 正面"face",反面"back"
     * @return
     */
    @ApiOperation(value = "身份证识别", notes = "")
    @RequestMapping(value = {"/idcard"}, method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "base64IdCard", value = "身份证base64编码", required = true),
            @ApiImplicitParam(name = "side", value = "身份证正反面", required = true)
    })
    public BizResult<IdCardVO> idcard(@RequestParam String base64IdCard, @RequestParam String side) {
        String appcode = ossConfig.getAppCode();
        String ocrHost = ossConfig.getOcrHost();
        String ocrIdcardPath = ossConfig.getOcrIdcardPath();
        String method = "POST";
        Map<String, String> headers = new HashMap<>(64);
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<>(64);

        // 对图像进行base64编码
        String imgBase64 = base64IdCard;
        byte[] bytes = Base64.decodeBase64(imgBase64);
        //1.5m
        if (bytes.length > 1572864) {
            log.info("身份证照片太大!");
            return BizResult.create(ErrorCodeEnum.IDCARD_IMAGE_TOO_LARGE.getErrCode(), ErrorCodeEnum.IDCARD_IMAGE_TOO_LARGE.getErrMsg());
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            JSONObject configObj = new JSONObject();
            JSONObject obj = new JSONObject();
            JSONArray inputArray = new JSONArray();
            configObj.put("side", side);
            obj.put("image", getParam(50, imgBase64));
            obj.put("configure", getParam(50, configObj.toString()));
            inputArray.put(obj);
            requestObj.put("inputs", inputArray);

            String body = requestObj.toString();

            HttpResponse response = HttpUtils.doPost(ocrHost, ocrIdcardPath, method, headers, querys, body);
            //获取response的body
            String output = EntityUtils.toString(response.getEntity());
            JSONObject resultObj = new JSONObject(output);
            JSONArray outputArray = resultObj.getJSONArray("outputs");
            String outputJson = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
            JSONObject out = new JSONObject(outputJson);
            if (out.getBoolean("success")) {
                IdCardVO idCardVO = parseIdCard(out, side);
                log.info("idCardVO:{}", JSON.toJSONString(idCardVO));
                return BizResult.create(idCardVO);
            } else {
                log.info("predict error");
                return BizResult.create(ErrorCodeEnum.FAILURE.getErrCode(), ErrorCodeEnum.SYS_ERROR.getErrMsg());
            }
        } catch (Exception e) {
            log.error("Exception", e);
            return BizResult.create(ErrorCodeEnum.SYS_ERROR.getErrCode(), ErrorCodeEnum.SYS_ERROR.getErrMsg());
        }
    }


    private static JSONObject getParam(int type, String dataValue) throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("dataType", type);
        obj.put("dataValue", dataValue);
        return obj;
    }

    /**
     * 解析身份证
     * @param side 正面"face",反面"back"
     * @return
     */
    private IdCardVO parseIdCard(JSONObject out, String side){
        IdCardVO idCardVO = new IdCardVO();
        if(IdCardSideEnum.FACE.getCode().equals(side)) {
            String addr = out.getString("address"); // 获取地址
            String name = out.getString("name"); // 获取名字
            String num = out.getString("num"); // 获取身份证号
            idCardVO.setAddr(addr);
            idCardVO.setName(name);
            idCardVO.setNum(num);
        }else if(IdCardSideEnum.BACK.getCode().equals(side)) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime end = DateUtil.defaultParseStringToDateTime(out.getString("end_date"));// 有效期结束时间 19800101
            if(end.isBefore(now)){
                idCardVO.setValid(Boolean.FALSE);
            }else{
                idCardVO.setValid(Boolean.TRUE);
            }

        }
        return idCardVO;
    }

}